import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';


import ProductListComponent from './list/ProductListComponent.js';
import ProductForm from './product_form/ProductForm.js';
import AddProductForm from './product_form/AddProductForm.js';
import TrainingModel from '../models/TrainingModel'
import TrainingSaleProductForm from './product_form/TrainingSaleProductForm'
import VAESaleProductForm from './product_form/VAESaleProductForm'
import VAEModel from '../models/VAEModel'

const template = require('./templates/RootComponent.mustache');

const RootComponent = Mn.View.extend({
    template: template,
    regions: {
        main: '.main',
        modalRegion: '.modal-container'
    },
    ui: {},
    // Listen to the current's view events
    events: {},
    // Listen to child view events
    childViewEvents: {
        'list:filter': 'onListFilter',
        'list:navigate': 'onListNavigate',
    },
    // Bubble up child view events
    childViewTriggers: {
    },
    initialize(){
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.filter_model = this.facade.request('get:model', 'ui_list_filter');
    },
    index(){
        /*
         * Show the List view
         */
        const collection = this.facade.request('get:collection', 'products');
        this.showChildView(
            'main', new ProductListComponent({
                collection: collection,
            })
        );
    },
    templateContext(){
        return {};
    },
    isLoaded(){
        /*
         * Check if datas has already been loaded (can not be the case in case
         * of other route income)
         */
        return ! _.isUndefined(this.collection)
    },
    showAddProductForm(model, collection){
        /*
         * Launched when an add button is clicked, build a temporary model and
         * shows the add form
         */

        let view = new AddProductForm(
            {
                model: model,
                destCollection: collection
            }
        );
        this.showChildView('main', view);
    },
    /** Returns the propper form class depending on model type
     *
     * @param model BaseProductModel class (or child class)
     * @returns ProductForm class (or child class)
     */
    _getFormFactory(model) {
        if (model instanceof TrainingModel) {
            return TrainingSaleProductForm
        } else if (model instanceof VAEModel) {
            return VAESaleProductForm
        } else {
            return ProductForm
        }
    },
    showEditProductForm(model){
        const FormFactory = this._getFormFactory(model)
        let view = new FormFactory(
            {
                model: model,
                destCollection: model.collection,
            }
        );
        this.showChildView('main', view);
    },
    showModal(view){
        this.showChildView('modalRegion', view);
    }
});
export default RootComponent
